<template>

  <a-layout>

    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <p>
        <a-form
            layout="inline"
            :model="param"
        >
          <a-form-item>
            <a-input v-model:value="param.name" placeholder="一级文档名称">
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleQuery({})">
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="add()">
              新增
            </a-button>
          </a-form-item>
        </a-form>
      </p>

      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="level1"
          :loading="loading"
          :pagination="false"
      >
        <template #cover="{text:cover}">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>

        <template v-slot:action="{text,record}">
          <a-space size="small">
            <a-button type="primary" @click="edit(record)">
              编辑
            </a-button>

            <a-popconfirm
                title="删除后不可恢复，确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
            >
              <a-button type="danger">
                删除
              </a-button>
            </a-popconfirm>

          </a-space>
        </template>
      </a-table>

    </a-layout-content>
  </a-layout>

  <a-modal
      title="文档表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
  >

    <a-form :model="doc" :label-col="{span: 6}">
      <a-form-item label="名称">
        <a-input v-model:value="doc.name"/>
      </a-form-item>
      <a-form-item label="父文档">
        <a-tree-select
            v-model:value="doc.parent"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="treeSelectData"
            placeholder="请选择父文档"
            tree-default-expand-all
            :replaceFields="{title:'name',key:'id',value:'id'}"
        >
        </a-tree-select>
      </a-form-item>
      <!--<a-form-item label="父文档">-->
      <!--  <a-select-->
      <!--      ref="select"-->
      <!--      v-model:value="doc.parent"-->
      <!--  >-->
      <!--    <a-select-option value="0">无</a-select-option>-->
      <!--    <a-select-option v-for="c in level1" :key="c.id" :value="c.id"-->
      <!--                     :disabled="doc.id==c.id">-->
      <!--      {{ c.name }}-->
      <!--    </a-select-option>-->
      <!--  </a-select>-->

      <!--</a-form-item>-->
      <a-form-item label="顺序">
        <a-input v-model:value="doc.sort"/>
      </a-form-item>
    </a-form>

  </a-modal>
</template>

<script lang="ts">
import {createVNode, defineComponent, onMounted, ref} from "vue";
import axios from "axios";
import {message, Modal} from 'ant-design-vue';
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";

export default defineComponent({
  name: 'AdminDoc',
  setup() {
    const route = useRoute();
    const param = ref();
    param.value = {};
    const docs = ref();
    const loading = ref(false);

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '父文档',
        dataIndex: 'parent',
        slots: {customRender: 'parent'}
      },
      {
        title: '顺序',
        dataIndex: 'sort',
        slots: {customRender: 'sort'}
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      },
    ]

    const level1 = ref();

    /**
     * 数据查询
     */
    const handleQuery = (params: any) => {
      loading.value = true;
      level1.value=[];
      axios.get("/doc/all", {
        params:{
          page:params.page,
          size:params.size,
          name:param.value.name
        }
      }).then((response) => {

        loading.value = false;
        const data = response.data;
        if (data.success){
          docs.value=data.content;
          console.log("原始数据：",docs.value);

          level1.value = [];
          level1.value = Tool.array2Tree(docs.value,0);

          console.log("树形结构：",level1);
        }else {
          message.error(data.message);
        }
      });
    };


    //------------------ 表单 ------------------
    const treeSelectData=ref();
    treeSelectData.value=[];
    const doc = ref({});
    const modalVisible = ref(false);
    const modalLoading = ref(false);

    const handleModalOk = () => {
      modalLoading.value = true;

      axios.post("/doc/save", doc.value).then((response) => {
        //后端有返回就去掉loading效果
        modalLoading.value=false;
        const data = response.data; //data就是后端的返回值CommonResp
        if (data.success){
          modalVisible.value = false;

          //重新加载列表
          handleQuery({});
        }else {
          message.error(data.message);
        }
      });
    };

    /**
     * 将某节点及其子孙结点全部置为disabled
     * @param treeSelectData
     * @param id
     */
    const setDisabled = (treeSelectData : any, id: any) =>{
      for(let i =0;i<treeSelectData.length;i++){
        const node = treeSelectData[i];
        if(node.id === id){
          node.disabled=true;
          const children = node.children;
          if(Tool.isNotEmpty(children)){
            for(let j=0;j<children.length;j++){
              setDisabled(children,children[j].id);
            }
          }
        }
        else {
          const children = node.children;
          if(Tool.isNotEmpty(children)){
            setDisabled(children,id);
          }
        }
      }
    }

    const deleteIds:Array<string>=[];
    const deleteNames: Array<string> = [];
    /**
     * 获取节点下所有子节点
     * @param treeSelectData
     * @param id
     */
    const getDeleteIds = (treeSelectData : any, id: any) =>{
      for(let i =0;i<treeSelectData.length;i++){
        const node = treeSelectData[i];
        if(node.id === id){
          //将目标Id放入结果集deleteIds
          deleteIds.push(id);
          deleteNames.push(node.name);
          const children = node.children;
          if(Tool.isNotEmpty(children)){
            for(let j=0;j<children.length;j++){
              getDeleteIds(children,children[j].id);
            }
          }
        }
        else {
          const children = node.children;
          if(Tool.isNotEmpty(children)){
            getDeleteIds(children,id);
          }
        }
      }
    };

    /**
     * 编辑
     */
    const edit = (record: any)=>{
      modalVisible.value=true;
      doc.value=Tool.copy(record);

      treeSelectData.value = Tool.copy(level1.value);
      setDisabled(treeSelectData.value,record.id);

      treeSelectData.value.unshift({id:0,name:'无'});
    };

    /**
     * 新增
     */
    const add = ()=>{
      modalVisible.value=true;
      doc.value={
        ebookId: route.query.ebookId
      };

      treeSelectData.value = Tool.copy(level1.value);

      treeSelectData.value.unshift({id: 0,name: '无'});
    };

    /**
     * 删除
     */
    const handleDelete = (id:number)=> {
      // 清空数组，否则多次删除时，数组会一直增加
      deleteIds.length = 0;
      deleteNames.length = 0;
      getDeleteIds(level1.value, id);
      Modal.confirm({
        title: '重要提醒',
        icon: createVNode(ExclamationCircleOutlined),
        content: '将删除：【' + deleteNames.join("，") + "】删除后不可恢复，确认删除？",
        onOk() {
          // console.log(ids)
          axios.delete("/doc/delete/" + deleteIds.join(",")).then((response) => {
            const data = response.data; // data = commonResp
            if (data.success) {
              // 重新加载列表
              handleQuery({});
            } else {
              message.error(data.message);
            }
          });
        },
      });
    }

    onMounted(()=>{
      handleQuery({});
    });

    return {
      level1,
      // docs,
      columns,
      loading,
      handleQuery,

      edit,
      add,
      handleDelete,

      modalVisible,
      modalLoading,
      handleModalOk,
      doc,
      param,
      treeSelectData,
    }
  }
});
</script>

<style>
  img {
    width: 50px!important;
    height: 50px!important;
  }
</style>